package com.mbbb.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mbbb.dao.TravelGroupDao;
import com.mbbb.pojo.TravelGroup;
import com.mbbb.service.TravelGroupService;
import com.mbbb.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;


@Service(interfaceClass = TravelGroupService.class)
@Transactional
public class TravelGroupServiceImpl implements TravelGroupService {

    @Autowired
    TravelGroupDao travelGroupDao;

    @Override
    public void add(Integer[] travelItemIds, TravelGroup travelGroup) {
        travelGroupDao.add(travelGroup);
        
        //主键回填：添加表单数据到数据库，MyBatis可以获取自动分配的主键，并赋值给实体对象
        Integer travelGroupId = travelGroup.getId();
        
        setTravelGroupAndTravelItem(travelGroupId,travelItemIds);
    }

    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        Page page = travelGroupDao.findPage(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public TravelGroup get(Integer id) {
        return travelGroupDao.get(id);
    }

    @Override
    public Integer[] getTravelItemIdByTravelGroupId(Integer id) {
        return travelGroupDao.getTravelItemIdByTravelGroupId(id);
    }

    @Override
    public void delete(Integer id) throws RuntimeException{
        int count = travelGroupDao.findTravelItemIdByTravelGroupId(id);
        if (count>0)
            throw new RuntimeException("先解除关系，再删除");
        travelGroupDao.delete(id);
    }

    @Override
    public void update(Integer[] travelItemIds, TravelGroup travelGroup) {
        travelGroupDao.update(travelGroup);

       //先删除旧的关系数据
        travelGroupDao.deleteAnd(travelGroup.getId());

        //重新增加一批新的关系数据，添加到中间表
        setTravelGroupAndTravelItem(travelGroup.getId(),travelItemIds);
    }

    @Override
    public List<TravelGroup> findAll() {
        return travelGroupDao.findAll();
    }

    //共有的方法
    private void setTravelGroupAndTravelItem(Integer travelGroupId, Integer[] travelItemIds) {

        if (travelItemIds!=null && travelItemIds.length>0) {
            for (Integer travelItemId : travelItemIds) {
                HashMap map = new HashMap();
                map.put("travelGroupId",travelGroupId);
                map.put("travelItemId",travelItemId);

                travelGroupDao.setTravelGroupAndTravelItem(map);
            }
        }
    }
}
